package com.jueyue.dao.parse.sqls;

import java.util.LinkedHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class InnerStack {

	private static final String ENDMARK = "*/";
	private static final String STARTMARK = "\n/*";
	private static final String LINESTARTMARK = "\n/*";

	LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();

	static final Pattern ptn = Pattern.compile("(?<=^\n/[*])(.*)(?=[*]/)");
	LinkedCharArray list = new LinkedCharArray();
	LinkedCharArray cmts = new LinkedCharArray();
	String key = null;
	boolean inNormalComment;

	public void eat(int c) {
		if (inNormalComment) {
			if (cmts.push(c).endsWith(ENDMARK)) {
				cmts.clear();
				inNormalComment = false;
			}
		} else if (key != null) {
			if (list.push(c).endsWith(LINESTARTMARK)) {
				list.popLast(3);
				addOne();
				list.push(LINESTARTMARK);
			} else if (list.endsWith(STARTMARK)) {
				list.popLast(2);
				inNormalComment = true;
			}
		} else {
			if (list.size() < 3) {
				if (!LINESTARTMARK.startsWith(list.push(c).toString())) {
					list.clear();
				}
			} else {
				if (list.push(c).endsWith(ENDMARK)) {
					Matcher matcher = ptn.matcher(list.popAll());
					if (matcher.find()) {
						key = matcher.group().trim();
					}
				}
			}
		}
	}

	public void addOne() {
		String value = list.popAll().trim();
		map.put(key, value);
		key = null;
	}

}
